// 表格
const tableList = document.querySelector('.list')
// 获取添加按钮的DOM对象
const insert = document.querySelector('.insert')
// 获取添加弹窗的DOM对象
const insertShow = document.querySelector('.insertShow')
// 获取添加弹窗的输入框DOM对象
const inputs = document.querySelectorAll('.insertShow input')
// 获取添加弹窗select的DOM对象
const insertShowSelect = document.querySelector('.insertShow select[name="faculty"]')
// 获取添加弹窗取消按钮的DOM对象
const cancel = document.querySelector('.cancel')
// 获取添加弹窗添加按钮的DOM对象
const add = document.querySelector('.add')

// 控件栏DOM对象
const first = document.querySelector('.first')
const last = document.querySelector('.last')
const next = document.querySelector('.next')
const theLast = document.querySelector('.theLast')
const paged = document.querySelector('.paged')
// 页码总数DOM对象
const pageSum = document.querySelector('.controlTable select')
const allPage = document.querySelector('.allPage')

// 页码
let page = 1
let pageNumber = 5
// 记录更新前的院系号
let oldProfessMajorId
// 记录当前页数据行数量
let trNumber
// 记录最大页数
let maxPage = 0

// 区分新增还是修改
let statusWhich = 0
// 记录旧的更新序号
let oldUpdateId

// 渲染专业
async function showAllProfessionMajor() {
  const result = (await axios({
    url: 'http://127.0.0.1:8080/Root/ProfessionMajor/getAllProfessionMajor',
    params: {
      page,
      pageNumber
    }
  })).data.data
  const htmlStr = await Promise.all(result.map(async (e, key) => {
    const facultiesName = await getFacultiesNameById(e.facultiesId)
    return `
      <tr data-id="${key}">
        <td>${e.id}</td>
        <td>${e.name}</td>
        <td>${e.sum}</td>
        <td>${facultiesName}</td>
        <td>
          <button class="update" data-id="${key}">修改</button>
          <button class="delete" data-id="${key}">删除</button>
        </td>
      </tr>
    `
  }))
  tableList.innerHTML = htmlStr.join('')
}

// 根据id获取院系
async function getFacultiesNameById(facultiesId) {
  const result = (await axios({
    url: 'http://127.0.0.1:8080/Root/ProfessionMajor/getFacultiesName',
    params: {
      id: facultiesId
    }
  })).data.data
  return result
}

showAllProfessionMajor()    // 初始化
getMaxPage()

function insertShowDisplay() {
  return (async () => {
    insertShow.style.display = 'block'
    const result = (await axios({
      url: 'http://127.0.0.1:8080/Root/ProfessionMajor/getAllFacultiesInformation'
    })).data.data
    const htmlStr = result.map(e => {
      return `
      <option value="${e.id}">${e.name}</option>
    `
    }).join('')
    insertShowSelect.innerHTML = htmlStr
  })
}


// 打开插入界面
insert.addEventListener('click', () => {
  statusWhich = 0
  add.innerHTML = '添加'
  !insertShowDisplay()()
})

// 更新专业
tableList.addEventListener('click', async (e) => {
  statusWhich = 1         // 设置为更新标记
  add.innerHTML = '更新'
  const element = e.target
  if (!element.classList.contains('update')) {
    return
  }
  !insertShowDisplay()()
  const updateId = oldUpdateId = document.querySelector(`.list tr[data-id="${element.dataset.id}"] td:nth-child(1)`).innerHTML
  // 获取回显数据
  const result = (await axios({
    url: 'http://127.0.0.1:8080/Root/ProfessionMajor/updateProfessionMajorInformation',
    params: {
      id: updateId
    }
  })).data.data
  inputs[0].value = result.id
  inputs[1].value = result.name
  // 回显所属院系
  const name = await getFacultiesNameById(result.facultiesId)
  for (let i = 0; i < insertShowSelect.options.length; i++) {
    const option = insertShowSelect.options[i]
    if (option.text === name) {
      insertShowSelect.selectedIndex = i
      break
    }
  }
})

// 删除专业
tableList.addEventListener('click', (e) => {
  const element = e.target
  if (!element.classList.contains('delete')) {
    return
  }
  const deleteId = document.querySelector(`.list tr[data-id="${element.dataset.id}"] td:nth-child(1)`).innerHTML
  const isDelete = confirm(`确认要删除专业号为${deleteId}的专业吗?`)
  if (!isDelete) {
    return
  }
  axios({
    url: 'http://127.0.0.1:8080/Root/ProfessionMajor/deleteProfessionMajor',
    method: 'POST',
    params: {
      id: deleteId
    }
  }).then(() => {
    getMaxPage()
    showAllProfessionMajor()
  })
})



// 退出插入界面
cancel.addEventListener('click', () => {
  insertShow.style.display = 'none'
  inputs[0].value = inputs[1].value = ''
})

// 添加专业
function addNewProfessionMajor() {
  const professionId = inputs[0].value
  if (!/^\d{2}$/.test(professionId)) {
    alert('专业号不符合规范')
    return
  }
  const professionName = inputs[1].value
  if (!/^[\u4e00-\u9fa5]{1,15}$/.test(professionName)) {
    alert('专业名称不符合规范')
    return
  }
  const facultyId = insertShowSelect.value
  axios({
    url: 'http://127.0.0.1:8080/Root/ProfessionMajor/addNewProfessionMajor',
    method: 'POST',
    data: {
      id: professionId,
      name: professionName,
      facultiesId: facultyId
    }
  }).then(() => {
    insertShow.style.display = 'none'
    inputs[0].value = inputs[1].value = ''
    getMaxPage()
    showAllProfessionMajor()
  }).catch(() => {
    alert('相应专业号已存在')
  })
}

// 修改专业
function updateNewProfessionMajor() {
  const id = inputs[0].value
  const name = inputs[1].value
  const facultiesId = insertShowSelect.value
  axios({
    url: 'http://127.0.0.1:8080/Root/ProfessionMajor/updateProfessionMajor?oldId=' + oldUpdateId,
    method: 'POST',
    data: {
      id,
      name,
      facultiesId
    }
  }).then(() => {
    alert('更新成功')
    insertShow.style.display = 'none'
    showAllProfessionMajor()
  }).catch(() => {
    alert('专业号已存在')
  })
}


add.addEventListener('click', () => {
  if (statusWhich === 0) {
    addNewProfessionMajor()
  } else {
    updateNewProfessionMajor()
  }
})

// 获取最大页数
function getMaxPage() {
  axios({
    url: 'http://127.0.0.1:8080/Root/ProfessionMajor/getAllPage',
    params: {
      page,
      pageNumber
    }
  }).then(result => {
    allPage.innerHTML = maxPage = result.data.data
  })
}

// 表格控件监听
first.addEventListener('click', () => {
  page = 1
  showAllProfessionMajor(page, pageNumber)
})

last.addEventListener('click', () => {
  if (page > 1) {
    showAllProfessionMajor(--page, pageNumber)
  }
})

next.addEventListener('click', () => {
  getMaxPage()
  if (page < maxPage) {
    showAllProfessionMajor(++page, pageNumber)
  }
})

theLast.addEventListener('click', () => {
  page = maxPage
  showAllProfessionMajor(page, pageNumber)
})

pageSum.addEventListener('change', () => {
  pageNumber = pageSum.value
  page = 1
  showAllProfessionMajor(page, pageNumber)
  getPageSum()
})

paged.addEventListener('change', () => {
  page = paged.value
  // 限定page范围
  page = page > maxPage ? maxPage : page
  page = page < 1 ? 1 : page
  showAllProfessionMajor(page, pageNumber)
})